/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-02-26 15:58:39
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-20 14:34:13
 */
// pages/cart/index.js
import {
  orderAPI,
  goodsAPI
} from './../../api/index'
import {
  returnStatus,
  returnStatusToast
} from './../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: [],
    selectAll: false,
    isSKU: false,
    cartId: 0,
    showBuy: true,
    sumPrice: 0,
    nvabarData:{
      showCapsule: 0
    }
  },

  onChange(event) {
    this.setData({
      result: event.detail
    });
    this.setData({
      selectAll: this.data.result.length === this.data.carList.length
    })
    console.log('tag', event)
    this.computePrice()
  },
  onSelectAll() {
    if (this.data.selectAll) {
      this.data.result.length = 0
    } else {
      this.data.carList.forEach((item, index) => {
        this.data.result.push(item.cartId + '_' + item.productId + '_' + index)
      })
    }
    this.setData({
      result: this.data.result,
      selectAll: !this.data.selectAll
    })
    this.computePrice()
  },
  // 合计价格
  computePrice() {
    const sum = this.data.result.reduce((acc, cur) => {
      const index = cur.split('_')[2]
      const goods = this.data.carList[index]
      const cur_price = goods.price * goods.quantity
      return acc + cur_price
    }, 0);
    this.setData({
      sumPrice: Number(sum).toFixed(2)
    })
  },
  // 导航去商品详情
  toDetail({
    detail,
    target: {
      dataset: {
        cartid: id
      }
    }
  }) {
    if (detail === 'cell') {
      wx.navigateTo({
        url: `/pages/goods/detail/index?id=${id}`,
      })
    }
  },
  // 选择sku
  closeSKU() {
    this.setData({
      isSKU: false
    })
  },
  showSKU({
    currentTarget: {
      dataset: {
        goods_info
      }
    }
  }) {
    const g = goods_info
    this.setData({
      goodsId: g.productId,
      cartId: g.cartId,
      initSku: {
        colorVal: g.productColor,
        sizeVal: g.productSize,
        count: g.quantity,
        priceDuration: g.price,
        max: g.storageQuantity
      },
      isSKU: true
    })
  },
  async modifyCartSku({
    detail: {
      quantity,
      storageId
    }
  }) {
    const res = orderAPI.modifyCart({
      "cartId": this.data.cartId,
      quantity,
      storageId
    })
    res.title = "修改成功"
    await returnStatusToast(res)
    this.setData({
      isSKU: false
    })
    this.queryInitCart()

  },
  async updateCount({
    detail: quantity,
    target: {
      dataset: {
        cartid
      }
    }
  }) {
    let res = await orderAPI.modifyCount({
      quantity,
      cartId: cartid
    })
    let _ = await returnStatus(res)
    console.log(_)
    if (_) {
      wx.showToast({
        title: '修改成功',
        icon: 'none',
      });
      this.queryInitCart()
    }
  },
  // 加入收藏夹
  async joinCollect({
    currentTarget: {
      dataset: {
        productid
      }
    }
  }) {
    const data = this.data.result.map(item => {
      return item.split('_')[1] * 1
    })
    if (productid && data.length === 0) return
    const res = await goodsAPI.joinCollectAll(
      productid ? [productid] : data
    )
    res.title = "收藏成功！"
    returnStatusToast(res)
  },
  // 移除购物车
  async removeCart({
    currentTarget: {
      dataset: {
        id
      }
    }
  }) {
    const data = this.data.result.map(item => {
      return item.split('_')[0] * 1
    })
    const res = await orderAPI.dropCart(
      id ? [id] : data
    )
    res.title = '移除成功'
    returnStatusToast(res, () => {
      this.queryInitCart()
    })
  },
  onClose({
    detail: {
      position,
      instance
    }
  }) {
    if (position === 'right') {
      instance.close();
    }
  },
  // 提交订单
  onSubmitFromCart() {
    const result = this.data.result
    let cartIds = []
    if (result.length === 0) {
      wx.showToast({
        title: '未选择商品',
        icon: 'none',
      });
      return false
    }
    // 判断所选商品库存情况
    let index = result.length
    while (index > 0) {
      index--
      const curGoods = this.data.carList[result[index].split('_')[2]]
      cartIds.push(curGoods.cartId)
      if (curGoods.quantity > curGoods.storageQuantity) {
        wx.showToast({
          title: `商品${curGoods.productName}库存不足`,
          icon: 'none',
        });
        index = -1
        return
      }
    }
    orderAPI.submitOrder({
        cartIds,
        orderFrom: 3
      })
      .then(async res => {
        const _ = await returnStatus(res)
        if (_) {
          // 返回确认订单id
          // 获取到id传递到确认订单那里
          wx.redirectTo({
            url: `/pages/queryOrder/index?orderId=${_}`
          });

        }
      })
      .catch(_ => {
        console.log(_)
      })
  },

  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},

  queryInitCart() {
    // 获取购物车列表
    orderAPI.handleCart({
      method: 'get'
    }).then(async res => {
      const carList = await returnStatus(res)
      this.setData({
        carList
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let modellers = wx.getStorageSync('modellers');
    var appInst =  getApp();
    let isIphoneX = appInst.globalData.isIphoneX;
    this.setData({
      isIphoneX,
      carList:[]
    })
    var appInst = getApp();
    appInst.setTitle('购物车')

    this.queryInitCart()
    this.productIds = new Set
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        active: 3
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})